package cn.gov.cbrc.east.task;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.gov.cbrc.east.util.FileTruncate;


/**
 * 合并日志
 * @author 贾中华
 *
 */
public class MergeLogs {
	private static final Logger logger = LogManager.getLogger(MergeLogs.class);
	/**
	 * 将每个文件切片生成的日志合并成一个
	 * @param size 切片数量
	 * @param FileName 文件名称
	 * @return
	 * @throws InterruptedException 
	 */
	public static boolean Merge(List<FileTruncate> list){
		logger.info("正在生成日志，请稍等...");
		BufferedReader buffer = null;
		InputStreamReader inputStream = null;
		String tmpString = null;
		String taskId = list.get(0).getFileName()+".detail";
		JobLogFactory.delete(taskId);
		Logger logger2 = JobLogFactory.createLogger(taskId);
		//标记总共多少行
		int rows = 1;
		//错误行号
		int errorRowNo=0;
		List<File> fileList = new ArrayList<File>();
		try {
			for(FileTruncate fileTruncate:list){
				String logPath = "logs/job-"+fileTruncate.getLoggerName()+".log";
				File file = new File(logPath);
				if(file != null && file.exists()){
					inputStream = new InputStreamReader(new FileInputStream(file),"UTF-8");
					buffer = new BufferedReader(inputStream);
					while((tmpString = buffer.readLine()) != null){
						//计算错误行在总文件中的位置
						int n = Integer.parseInt(tmpString.substring(tmpString.indexOf("[")+1, tmpString.indexOf("]")));
						logger2.error(rows+"."+"line["+(errorRowNo+n)+"]"+tmpString.substring(tmpString.indexOf("]")+1, tmpString.length()));
						rows++;
					}
					errorRowNo += fileTruncate.getRow();
					//保存合并成功的文件到list
					buffer.close();
					inputStream.close();
					fileList.add(file);
				}
			}
		} catch (Exception e) {
			logger.error("合并日志失败",e);
		}finally{
			try {
				JobLogFactory.stop(taskId);
				if(buffer != null){
					buffer.close();
				}
				if(inputStream != null){
					inputStream.close();
				}
				for(File file:fileList){
					//已合并的日志文件删除
					file.delete();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return false;
	}
}
